const http = require('../../../utils/https.js');
Page({
    data: {
        appraiseNum: 0,
        appraise: [],
        productId: '',
        pageNum: 1,
        pageSize: 10,
        hasMore: true,
        averageScore: 0,
        scoreDistribution: [{
                score: 5,
                percentage: 0
            },
            {
                score: 4,
                percentage: 0
            },
            {
                score: 3,
                percentage: 0
            },
            {
                score: 2,
                percentage: 0
            },
            {
                score: 1,
                percentage: 0
            }
        ]
    },

    onLoad(options) {
        if (options && options.productId) {
            this.setData({
                productId: options.productId
            }, () => {
                this.getComments();
            });
            console.log('评论的商品的id:', options.productId);
        } else {
            wx.showToast({
                title: '获取商品信息失败',
                icon: 'none'
            });
            setTimeout(() => wx.navigateBack(), 1500);
        }
    },

    getComments(isLoadMore = false) {
        const {
            productId,
            pageNum,
            pageSize
        } = this.data;

        wx.showLoading({
            title: '加载中...',
            mask: true
        });

        http.GET(
            '/comment/reply/list', {
                productId,
                pageNum,
                pageSize
            },
            (res) => {
                wx.hideLoading();

                if (res.code === 200 && res.rows) {
                    const comments = res.rows.map(item => {
                        const comment = item.comment || {};

                        let imgUrls = [];
                        if (comment.imageUrls) {
                            imgUrls = comment.imageUrls.split(',').map(url => url.trim());
                        } else if (comment.imageUrlList && comment.imageUrlList.length > 0) {
                            imgUrls = comment.imageUrlList;
                        }

                        return {
                            id: comment.id,
                            avatarUrl: item.avatar || comment.avatar || '',
                            name: comment.userName || item.userName || '匿名用户',
                            time: this.formatTime(comment.createTime || item.createdAt),
                            score: comment.rating ? Math.round(comment.rating / 2) : 5,
                            text: comment.content || '',
                            imgUrls: imgUrls,
                            reply: item.content || '' // 商家回复
                        };
                    });

                    let newComments = [];
                    if (isLoadMore) {
                        newComments = [...this.data.appraise, ...comments];
                    } else {
                        newComments = comments;
                        this.calculateScoreStats(res.rows.map(r => r.comment));
                    }

                    this.setData({
                        appraise: newComments,
                        appraiseNum: res.total || 0,
                        hasMore: res.rows.length >= pageSize
                    });
                } else {
                    wx.showToast({
                        title: '获取评论失败',
                        icon: 'none'
                    });
                }
            },
            (err) => {
                wx.hideLoading();
                wx.showToast({
                    title: '评论加载失败',
                    icon: 'none'
                });
                console.error('获取评论失败:', err);
            }
        );
    },

    calculateScoreStats(comments) {
        if (!comments || comments.length === 0) return;

        let totalScore = 0;
        const scoreCounts = [0, 0, 0, 0, 0];

        comments.forEach(comment => {
            const score = comment.rating ? Math.round(comment.rating / 2) : 5;
            totalScore += score;
            scoreCounts[score - 1]++;
        });

        const averageScore = (totalScore / comments.length).toFixed(1);
        const total = comments.length;
        const scoreDistribution = [{
                score: 5,
                percentage: Math.round(scoreCounts[4] / total * 100)
            },
            {
                score: 4,
                percentage: Math.round(scoreCounts[3] / total * 100)
            },
            {
                score: 3,
                percentage: Math.round(scoreCounts[2] / total * 100)
            },
            {
                score: 2,
                percentage: Math.round(scoreCounts[1] / total * 100)
            },
            {
                score: 1,
                percentage: Math.round(scoreCounts[0] / total * 100)
            }
        ];

        this.setData({
            averageScore,
            scoreDistribution
        });
    },

    loadMoreComments() {
        if (!this.data.hasMore) return;

        this.setData({
            pageNum: this.data.pageNum + 1
        }, () => {
            this.getComments(true);
        });
    },

    formatTime(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },

    onPullDownRefresh() {
        this.setData({
            pageNum: 1,
            hasMore: true
        }, () => {
            this.getComments().then(() => wx.stopPullDownRefresh());
        });
    },

    onReachBottom() {
        this.loadMoreComments();
    },

    onShareAppMessage() {
        return {
            title: '商品评价',
            path: `/index/pages/mzhGoodsReviews/mzhGoodsReviews?productId=${this.data.productId}`
        };
    }
});
